//
//  LivestockMapViewController.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/10.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "LivestockMapViewController.h"
#import "LivestockSettingViewController.h"
#import "MKMapView+ZoomLevel.h"
#import "LivestockMapBottomView.h"
#import "MapBottomModel.h"
#import "LivestockPropertyViewController.h"
#import "GeoJson.h"
#import "BasicMapAnnotation.h"

typedef enum : NSInteger {
    TaskCollectionStatusReady,
    TaskCollectionStatusSave,
    TaskCollectionStatusCollecting,
} TaskCollectionStatus;

@interface LivestockMapViewController ()<MKMapViewDelegate>

@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UILabel *topLabel;
@property (nonatomic, strong) UIButton *mapBtn;
@property (nonatomic, strong) UIView *bottomReadyView;
@property (nonatomic, strong) UIView *bottomCollectingView;
@property (nonatomic, strong) UIButton *trackingBtn;
@property (nonatomic, strong) CLLocation *currentLocation;
@property (nonatomic, assign) BOOL showSatellite;
@property (nonatomic, assign) BOOL isPauseing;
@property (nonatomic, assign) BOOL moving;
@property (nonatomic, assign) BOOL firstLoaded;
@property (nonatomic, assign) NSUInteger currentMapLevel;
@property (nonatomic, strong) LivestockMapBottomView *pointView;
@property (nonatomic, strong) GeoJson *geoJson;
@property (nonatomic, strong) NSMutableArray *tempCoordinateArray;//临时存放的经纬度
@property (nonatomic, strong) NSMutableArray *coordinateArray;//本地数据保存的记录点，放到内存中
@property (nonatomic, strong) NSMutableArray <UploadImageInfo *>*selectImagesArray;
@property (nonatomic, strong) NSMutableArray *stackViewArray;
@property (nonatomic, strong) NSMutableArray *polyLineArray;
@property (nonatomic, assign) TaskCollectionStatus collectionStatus;
@property (nonatomic, strong) MKPolyline *polyline;
@end

@implementation LivestockMapViewController

#pragma mark - Controller
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initParams];
    kWeakSelf
    [APP_DELEGATE getUserLocationWithonComplete:^(NSDictionary *data, NSError *error) {
        if (data) {
            if (!weakSelf.firstLoaded) {
                [weakSelf initUI];
                LocationInfo *info = data[@"data"];
                weakSelf.currentLocation = [[CLLocation alloc] initWithLatitude:info.coordinate.latitude longitude:info.coordinate.longitude];
                [weakSelf fitMapRegion];
                [weakSelf performSelector:@selector(addInitAnnotations) withObject:nil afterDelay:1];
            }
        } else {
            if (!weakSelf.firstLoaded) {
                [weakSelf initUI];
                [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(31.197414,121.586533) zoomLevel:15 animated:YES];
                weakSelf.firstLoaded = YES;
            }

        }
    }];
    //31.197414,121.586533
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
}

#pragma mark - Init
- (void)initParams {
    self.currentMapLevel = 17;
    self.showSatellite = NO;
    self.isPauseing = YES;
    self.firstLoaded = NO;
    self.moving = NO;
    self.coordinateArray = [NSMutableArray array];
    self.tempCoordinateArray = [NSMutableArray array];
    self.selectImagesArray = [NSMutableArray array];
    self.polyLineArray = [NSMutableArray array];
    self.collectionStatus = TaskCollectionStatusReady;
    
    if (!self.taskDetail.finished) {
        self.geoJson = [GeoJson getGeoJsonFromCache:self.taskDetail.searchCacheIDString];
        for (GeoFeature *feature in self.geoJson.features) {
            NSArray *locations = feature.geoMetry.coordinates;
            NSMutableArray *locationArray = [NSMutableArray array];
            if (self.taskDetail.isLine) {
                for (NSArray *coors in locations) {
                    if (coors.count > 1) {
                        CLLocation *location = [[CLLocation alloc] initWithLatitude:[coors[1] doubleValue] longitude:[coors[0] doubleValue]];
                        [locationArray addObject:location];
                    }
                }
            } else {
                if (locations.count > 1) {
                    CLLocation *location = [[CLLocation alloc] initWithLatitude:[locations[1] doubleValue] longitude:[locations[0] doubleValue]];
                    [locationArray addObject:location];
                }
            }
            [self.coordinateArray addObject:locationArray];
        }
    }
    
    self.stackViewArray = [NSMutableArray array];
    
    NSMutableArray *array = [NSMutableArray array];
    //第一种类型
    MapBottomModel *model = [[MapBottomModel alloc] init];
    model.title = self.taskDetail.isLine ? NSLocalizedString(@"开始", nil) : NSLocalizedString(@"保存", nil);
    model.image = self.taskDetail.isLine ? @"play" : @"save";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"完成", nil);
    model.image = @"finish";
    [array addObject:model];
    [self.stackViewArray addObject:array];
    
    //第二种类型
    array = [NSMutableArray array];
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"保存", nil);
    model.image = @"save";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"上传", nil);
    model.image = @"upload";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"完成", nil);
    model.image = @"finish";
    [array addObject:model];
    [self.stackViewArray addObject:array];

    //第三种类型
    array = [NSMutableArray array];
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"暂停", nil);
    model.image = @"pause";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"放弃", nil);
    model.image = @"delete";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"保存", nil);
    model.image = @"save";
    [array addObject:model];
    [self.stackViewArray addObject:array];

    //第四种类型
    array = [NSMutableArray array];
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"开始", nil);
    model.image = @"play";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"上传", nil);
    model.image = @"upload";
    [array addObject:model];
    
    model = [[MapBottomModel alloc] init];
    model.title = NSLocalizedString(@"完成", nil);
    model.image = @"finish";
    [array addObject:model];
    [self.stackViewArray addObject:array];

}

- (void)initUI {
    kWeakSelf
    UIBarButtonItem *rightBtn = [UIBarButtonItem barItemWithTitle:NSLocalizedString(@"设置", nil) target:self action:@selector(goSetting)];
    self.navigationItem.rightBarButtonItem = rightBtn;

    self.mapView = [[MKMapView alloc] init];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.rotateEnabled = NO;
    self.mapView.mapType = self.showSatellite ? MKMapTypeHybridFlyover : MKMapTypeStandard;
    [self.view addSubview:self.mapView];
    
    self.trackingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.trackingBtn setBackgroundImage:[UIImage imageNamed:@"homeLocation"] forState:UIControlStateNormal];
    self.trackingBtn.tappedBlock = ^(UIButton *btn) {
        weakSelf.moving = !weakSelf.moving;
        [weakSelf.trackingBtn setBackgroundImage:weakSelf.moving ? [UIImage imageNamed:@"homeLocation_selected"] : [UIImage imageNamed:@"homeLocation"] forState:UIControlStateNormal];
    };
    [self.mapView addSubview:self.trackingBtn];
    
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor blackColor];
    self.topView.alpha = 0.4;
    [self.view addSubview:self.topView];
    
    self.topLabel = [[UILabel alloc] init];
    self.topLabel.text = self.taskDetail.taskName;
    self.topLabel.numberOfLines = 2;
    self.topLabel.backgroundColor = [UIColor clearColor];
    self.topLabel.font = [UIFont systemFontOfSize:16];
    self.topLabel.textColor = [UIColor whiteColor];
    [self.topView addSubview:self.topLabel];
    
    self.mapBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.mapBtn setBackgroundImage:[UIImage imageNamed:@"icon_map"] forState:UIControlStateNormal];
    self.mapBtn.tappedBlock = ^(UIButton *btn) {
        weakSelf.showSatellite = !weakSelf.showSatellite;
        weakSelf.mapView.mapType = weakSelf.showSatellite ? MKMapTypeSatellite : MKMapTypeStandard;
        [weakSelf.mapBtn setBackgroundImage:weakSelf.showSatellite ? [UIImage imageNamed:@"satellite"] : [UIImage imageNamed:@"icon_map"] forState:UIControlStateNormal];
    };
    [self.view addSubview:self.mapBtn];
    
    
    NSArray *array = self.stackViewArray[0];
    self.pointView = [[LivestockMapBottomView alloc] initWithFrame:CGRectZero withTaskDtail:self.taskDetail array:array];
    [self.view addSubview:self.pointView];
    self.pointView.block = ^(NSInteger index) {
        [weakSelf doAction:index];
    };
    CGFloat spacing = (kScreenWidth - array.count * 40) / (array.count + 1);


    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.offset(0);
        make.bottom.equalTo(weakSelf.pointView.mas_top);
    }];
    [self.trackingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.offset(20);
        make.bottom.offset(-20);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.offset(0);
        make.height.mas_equalTo(60);
    }];
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.offset(20);
        make.trailing.offset(-20);
        make.centerY.offset(0);
    }];
    [self.mapBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.leading.offset(10);
        make.top.equalTo(weakSelf.topView.mas_bottom).offset(10);
    }];
    
    [self.pointView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.leading.offset(spacing);
        make.trailing.offset(-spacing);
        make.height.mas_equalTo((weakSelf.taskDetail.finished || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) ? 0 : 60);
    }];
    
    if ([self.taskDetail localPathExisted]) {
        [self setStackViewIndex:self.taskDetail.isLine ? 3 : 1];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self fitMapRegion];
}

- (GeoJson *)geoJson {
    if (!_geoJson) {
        _geoJson = [[GeoJson alloc] init];
        _geoJson.type = @"FeatureCollection";
    }
    return _geoJson;
}

- (CLLocation *)currentLocation {
    if (!_currentLocation) {
        _currentLocation = [[CLLocation alloc] init];
    }
    return _currentLocation;
}

#pragma mark - Action
- (void)goSetting {
    LivestockSettingViewController *vc = [[LivestockSettingViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)doAction:(NSInteger)index {
    if (self.currentLocation.coordinate.latitude <= 0 || self.currentLocation.coordinate.longitude <= 0) {
        return;
    }
    switch (self.collectionStatus) {
        case TaskCollectionStatusReady:
            if (index == 0) {
                if (self.taskDetail.isLine) {
                    [self taskStart];
                } else {
                    [self taskSave];
                }
            } else {
                [self taskFinish];
            }
            break;
        case TaskCollectionStatusCollecting:
            if (index == 0) {
                if (self.isPauseing) {
                    [self taskStart];
                } else {
                    [self taskPause];
                }
            } else if (index == 1) {
                [self taskGiveUp];
            } else {
                [self taskSave];
            }
            break;
        case TaskCollectionStatusSave:
            if (index == 0) {
                if (self.taskDetail.isLine) {
                    [self taskStart];
                } else {
                    [self taskSave];
                }
            } else if (index == 1) {
                [self taskUpload];
            } else {
                [self taskFinish];
            }
            break;
    }
}

- (void)taskStart {
    self.isPauseing = NO;
    [self setStackViewIndex:2];
}

- (void)taskFinish {
    kWeakSelf
    NSString *titleString = @"是否要结束任务?";
    if ([self.taskDetail localPathExisted]) {
        titleString = @"是否要放弃未上传的数据直接结束任务?";
    }
    [self jxt_showAlertWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(titleString, nil) appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.
        addActionCancelTitle(NSLocalizedString(@"取消", nil)).
        addActionDefaultTitle(NSLocalizedString(@"确定", nil));
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 1) {
            [self showWaitingIcon];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic safeSetObject:self.taskDetail.taskDetailID forKey:@"taskDetailID"];
            [TrackitDataEngine completeTaskDetail:dic onComplete:^(NSDictionary *data, NSError *error) {
                [weakSelf dismissWaitingIcon];
                if (data) {
                    //完成任务，删除本地的json和图片
                    [GeoJson deleteTaskCache:weakSelf.taskDetail.searchCacheIDString];
                    [weakSelf.coordinateArray removeAllObjects];
                    [weakSelf.selectImagesArray removeAllObjects];
                    weakSelf.taskDetail.finished = YES;
                    [weakSelf setStackViewIndex:0];
//                    [[NSNotificationCenter defaultCenter] postNotificationName:kTaskFinishNotification object:nil];
                } else {
                    [TKUtil showMessage:error.userInfo[@"message"]];
                }
            }];
        }
    }];
}

- (void)taskPause {
    self.isPauseing = !self.isPauseing;
    [self setStackViewIndex:0];
}

- (void)taskUpload {
    kWeakSelf
    GeoJson *geo = [GeoJson getGeoJsonFromCache:self.taskDetail.searchCacheIDString];
    if (!geo) {
        return;
    }
    
    [self showWaitingIcon];
    NSMutableDictionary *geojson = [GeoJson getGeoJson:geo];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic safeSetObject:self.taskDetail.taskDetailID forKey:@"taskDetailID"];
    [dic safeSetObject:[CommonFunction convertToJSONData:[geojson mutableCopy]] forKey:@"jsonData"];

    [TrackitDataEngine submitTaskDetail:dic onComplete:^(NSDictionary *data, NSError *error) {
        [weakSelf dismissWaitingIcon];
        if (data) {
            [TKUtil showMessage:data[@"Msg"]];
            [weakSelf setStackViewIndex:0];
            [APP_DELEGATE saveValue:NO withID:weakSelf.taskDetail.searchCacheIDString];
        } else {
            [TKUtil showMessage:error.userInfo[@"message"]];
        }
    }];
    
    for (GeoFeature *feature in geo.features) {
        NSArray *pics = feature.properties[@"Pictures"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        for (NSDictionary *dic in pics) {
            NSString *filePath = [[CommonFunction getTrackitCachePathByID:self.taskDetail.searchCacheIDString] stringByAppendingPathComponent:dic[@"localPath"]];
            if ([fileManager fileExistsAtPath:filePath]) {
                NSDateFormatter *dateFormatterSeq = [[NSDateFormatter alloc] init];
                dateFormatterSeq.dateFormat = @"YYYYMMdd";
                NSDate *date = [dateFormatterSeq dateFromString:dic[@"photoDate"]];
                dateFormatterSeq.dateFormat = @"YYYY/MM/dd";
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                [params safeSetObject:[NSString stringWithFormat:@"%ld" ,(long)[dic[@"taskDetailID"] integerValue]] forKey:@"taskDetailID"];
                [params safeSetObject:dic[@"objId"] forKey:@"objId"];
                [params safeSetObject:dic[@"photoSeq"] forKey:@"photoSeq"];
                [params safeSetObject:[dateFormatterSeq stringFromDate:date] forKey:@"photoDate"];
                NSData *imageData = [NSData dataWithContentsOfFile:filePath];
                [TrackitDataEngine uploadPhoto:imageData withParams:params onComplete:^(NSDictionary *data, NSError *error) {
                    if (data) {
                        [GeoJson deleteImagesCache:self.taskDetail.searchCacheIDString paths:@[filePath]];
                    }
                }];
            }
        }
    }
}

- (void)taskGiveUp {
    kWeakSelf
    [self jxt_showAlertWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"是否终止并放弃当前采集的轨迹数据", nil) appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.
        addActionCancelTitle(NSLocalizedString(@"取消", nil)).
        addActionDefaultTitle(NSLocalizedString(@"确定", nil));
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 1) {
            weakSelf.geoJson = nil;
            weakSelf.isPauseing = YES;
            [weakSelf setStackViewIndex:0];
            [weakSelf.selectImagesArray removeAllObjects];
            [weakSelf.tempCoordinateArray removeAllObjects];
        }
    }];

}

- (void)taskSave {
    if (self.tempCoordinateArray.count == 0) {
        [TKUtil showMessage:NSLocalizedString(@"没有数据可以保存", nil)];
        return;
    }
    self.isPauseing = YES;
    self.moving = NO;
    [self.trackingBtn setBackgroundImage:[UIImage imageNamed:@"homeLocation"] forState:UIControlStateNormal];
    kWeakSelf
    LivestockPropertyViewController *vc = [[LivestockPropertyViewController alloc] init];
    vc.taskDetail = self.taskDetail;
    vc.propertyBlock = ^(NSMutableDictionary *propertyDic, NSMutableArray *imageInfoArray, NSArray *images) {
        if (images.count > 0) {
            weakSelf.selectImagesArray = [NSMutableArray arrayWithArray:images];
        }

        //保存到本地数据
        GeoFeature *feature = [[GeoFeature alloc] init];
        feature.type = @"Feature";
        NSMutableArray *properties = [NSMutableArray arrayWithArray:imageInfoArray];
        NSMutableDictionary *dic = [propertyDic mutableCopy];
        [dic safeSetObject:properties forKey:@"Pictures"];
        feature.properties = dic;

        GeoMetry *metry = [[GeoMetry alloc] init];
        feature.geoMetry = metry;
        if (weakSelf.taskDetail.isLine) {
            [weakSelf setStackViewIndex:3];
            NSMutableArray *array = [NSMutableArray arrayWithArray:weakSelf.tempCoordinateArray];
            if (array.count > 0) {
                metry.type = GeometryTypeLineString;
                for (CLLocation *info in array) {
                    [metry.coordinates addObject:@[@(info.coordinate.longitude),@(info.coordinate.latitude)]];
                }
                [weakSelf.geoJson.features addObject:feature];
            }
        } else {
            [weakSelf setStackViewIndex:1];
            CLLocation *info = weakSelf.tempCoordinateArray.firstObject;
            if (info) {
                metry.type = GeometryTypePoint;
                metry.coordinates = [NSMutableArray arrayWithObjects:@(info.coordinate.longitude),@(info.coordinate.latitude), nil];
                [weakSelf.geoJson.features addObject:feature];
            }
        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:kTaskSaveLocalNotification object:nil];
        [weakSelf saveToCache];
        [APP_DELEGATE saveValue:YES withID:weakSelf.taskDetail.searchCacheIDString];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Private
- (void)setStackViewIndex:(NSInteger)index {
    self.collectionStatus = (TaskCollectionStatus)index;
    if (index >= 3) {
        self.collectionStatus = TaskCollectionStatusSave;
    }
    kWeakSelf
    NSArray *array = self.stackViewArray[index];
    [self.pointView resetSubviews:array];
    CGFloat spacing = (kScreenWidth - array.count * 40) / (array.count + 1);
    [self.pointView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.leading.offset(spacing);
        make.trailing.offset(-spacing);
        make.height.mas_equalTo(weakSelf.taskDetail.finished ? 0 : 60);
    }];
}

- (void)saveToCache {
    NSString *idString = self.taskDetail.searchCacheIDString;
    [GeoJson saveJsonToCache:idString geoJson:self.geoJson];
    [GeoJson saveImagesToCache:idString images:self.selectImagesArray];
    [self.coordinateArray addObject:[NSMutableArray arrayWithArray:self.tempCoordinateArray]];
    [self.tempCoordinateArray removeAllObjects];
    [self.selectImagesArray removeAllObjects];
    self.polyline = nil;
    [self addInitPolyline:self.coordinateArray collecting:NO];
}

- (void)fitMapRegion {
//    NSLog(@"%f,%f",APP_DELEGATE.locationInfo.coordinate.latitude,APP_DELEGATE.locationInfo.coordinate.longitude);
    [self.mapView setCenterCoordinate:APP_DELEGATE.locationInfo.coordinate zoomLevel:self.currentMapLevel animated:YES];
}

- (int)getZoomLevel:(MKMapView *)tempMapView {
    return 21 - round(log2(tempMapView.region.span.longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * tempMapView.bounds.size.width)));
}

- (void)addInitAnnotations {
    [self addInitPolyline:self.coordinateArray collecting:NO];
    self.firstLoaded = YES;
}

- (void)addAnnotations {
    MKMapPoint northEastPoint = MKMapPointMake(0.f, 0.f);
    MKMapPoint southWestPoint = MKMapPointMake(0.f, 0.f);
    NSMutableArray *totalArray = [NSMutableArray arrayWithArray:self.tempCoordinateArray];
    NSInteger pointCount = totalArray.count;
    // create a c array of points.
    MKMapPoint* pointArray = malloc(sizeof(CLLocationCoordinate2D) * pointCount);
    
    for (int idx = 0; idx < pointCount; idx++) {
        CLLocation *location = [totalArray objectAtIndex:idx];
        CLLocationDegrees latitude  = location.coordinate.latitude;
        CLLocationDegrees longitude = location.coordinate.longitude;
        
        // create our coordinate and add it to the correct spot in the array
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        MKMapPoint point = MKMapPointForCoordinate(coordinate);
        
        // if it is the first point, just use them, since we have nothing to compare to yet.
        if (idx == 0) {
            northEastPoint = point;
            southWestPoint = point;
        } else {
            if (point.x > northEastPoint.x)
                northEastPoint.x = point.x;
            if (point.y > northEastPoint.y)
                northEastPoint.y = point.y;
            if (point.x < southWestPoint.x)
                southWestPoint.x = point.x;
            if (point.y < southWestPoint.y)
                southWestPoint.y = point.y;
        }
        
        pointArray[idx] = point;
    }
    
    if (self.polyline) {
        [self.mapView removeOverlay:self.polyline];
    }
    
    self.polyline = [MKPolyline polylineWithPoints:pointArray count:pointCount];
    
    if (self.polyline) {
        [self.mapView addOverlay:self.polyline];
    }
    free(pointArray);
}

- (void)addInitPolyline:(NSMutableArray *)polyArray collecting:(BOOL)collecting {
    if (self.taskDetail.isLine) {
        NSMutableArray *totalArray = [NSMutableArray arrayWithArray:polyArray];
        for (MKPolyline *polyLine in self.polyLineArray) {
            [self.mapView removeOverlay:polyLine];
        }
        [self.polyLineArray removeAllObjects];
        for (int i = 0; i < totalArray.count; i++) {
            MKMapPoint northEastPoint = MKMapPointMake(0.f, 0.f);
            MKMapPoint southWestPoint = MKMapPointMake(0.f, 0.f);
            
            NSArray *array = totalArray[i];
            MKMapPoint *pointArray = malloc(sizeof(CLLocationCoordinate2D) * array.count);
            
            for (int idx = 0; idx < array.count; idx++) {
                
                CLLocation *location = array[idx];
                CLLocationDegrees latitude  = location.coordinate.latitude;
                CLLocationDegrees longitude = location.coordinate.longitude;
                
                // create our coordinate and add it to the correct spot in the array
                CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
                MKMapPoint point = MKMapPointForCoordinate(coordinate);
                
                // if it is the first point, just use them, since we have nothing to compare to yet.
                if (idx == 0) {
                    northEastPoint = point;
                    southWestPoint = point;
                } else {
                    if (point.x > northEastPoint.x)
                        northEastPoint.x = point.x;
                    if (point.y > northEastPoint.y)
                        northEastPoint.y = point.y;
                    if (point.x < southWestPoint.x)
                        southWestPoint.x = point.x;
                    if (point.y < southWestPoint.y)
                        southWestPoint.y = point.y;
                }
                
                pointArray[idx] = point;
            }
            MKPolyline *polyline = [MKPolyline polylineWithPoints:pointArray count:array.count];
            if (polyline) {
                [self.mapView addOverlay:polyline];
                [self.polyLineArray addObject:polyline];
            }
            free(pointArray);
        }
    } else {
        NSMutableArray *annotationArray = [NSMutableArray array];
        for (NSArray *array in polyArray) {
            if (array.count > 0) {
                CLLocation *info = array[0];
                BasicMapAnnotation *annotation = [[BasicMapAnnotation alloc] initWithLatitude:info.coordinate.latitude andLongitude:info.coordinate.longitude];
                [annotationArray addObject:annotation];
            }
        }
        [self.mapView addAnnotations:annotationArray];
    }
}

#pragma mark - MKMapView
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    self.currentMapLevel = [self getZoomLevel:mapView];
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    NSLog(@"%f,%f",userLocation.coordinate.latitude,userLocation.coordinate.longitude);
    if (userLocation.coordinate.latitude == 0 && userLocation.coordinate.longitude == 0) {
        return;
    }
    if ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied && !self.taskDetail.finished && self.pointView.height == 0) {
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(userLocation.coordinate.latitude, userLocation.coordinate.longitude) zoomLevel:self.currentMapLevel animated:YES];
        NSArray *array = self.stackViewArray[0];
        CGFloat spacing = (kScreenWidth - array.count * 40) / (array.count + 1);
        kWeakSelf
        [self.pointView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.bottom.offset(0);
            make.leading.offset(spacing);
            make.trailing.offset(-spacing);
            make.height.mas_equalTo(weakSelf.taskDetail.finished ? 0 : 60);
        }];
    } else {
        if (self.moving) {
            [mapView setCenterCoordinate:userLocation.coordinate zoomLevel:self.currentMapLevel animated:NO];
        }
    }

    CLLocation *location = [[CLLocation alloc] initWithLatitude:userLocation.coordinate.latitude
                                                      longitude:userLocation.coordinate.longitude];

    if (self.tempCoordinateArray.count > 0) {
        if (([self.currentLocation distanceFromLocation:location] < [APP_DELEGATE.user.intervalValue doubleValue])
            || ([self.currentLocation distanceFromLocation:location] > [APP_DELEGATE.user.distanceValue doubleValue])) {
            return;
        }
    }
    if (self.isPauseing && self.taskDetail.isLine) {
        return;
    }
    
#ifdef DEBUG
//    [TKUtil showMessage:[NSString stringWithFormat:@"取到点啦第%lu个",(unsigned long)self.tempCoordinateArray.count]];
#endif
    self.currentLocation = location;
    
    if (self.taskDetail.isLine) {
        [self.tempCoordinateArray addObject:location];
        [self addAnnotations];
    } else {
        self.tempCoordinateArray = [NSMutableArray arrayWithObject:location];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"annotationView"];
    if (!annotationView) {
        annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotationView"];
    }
    annotationView.image = [UIImage imageNamed:@"point"];
    return annotationView;
}

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        MKPolylineRenderer *overlayRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        overlayRenderer.strokeColor = [UIColor colorWithHex:0x228B22 alpha:1.0f];
        overlayRenderer.lineWidth = 2;
        return overlayRenderer;
    }
    return nil;
}
@end
